package com.hluobo.library.action;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import org.json.JSONException;
import org.json.JSONObject;

import com.hluobo.library.model.Book;
import com.hluobo.library.service.BookService;
import com.hluobo.library.util.StreamTool;
import com.opensymphony.xwork2.ActionSupport;

public class BookAction extends ActionSupport {

	private BookService bookService;
	private List<Book> books = new ArrayList<Book>();
	private String jsonParam;
	private int resCode = -1;
	private String msg = "err";

	@Override
	public String execute(){
		//{"name":"name","val":"java"}
		//jsonParam = "{\"name\":\"name\",\"val\":\"a\"}";
		try {
			JSONObject paramObj = new JSONObject(jsonParam);
			books = bookService.query(paramObj);
			if(books.size()>0){
				msg = "查询成功";
				resCode = 200;
			}else{
				msg = "无查询结果";
				resCode = 404;
			}
		} catch (JSONException e) {
			msg = "服务器错误";
			resCode = 500;
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String search(){
		
		try {
			JSONObject paramObj =  StreamTool.readRequstString();
			books = bookService.query(paramObj);
			if(books.size()>0){
				msg = "查询成功";
				resCode = 200;
			}else{
				msg = "无查询结果";
				resCode = 404;
			}
		} catch (Throwable e) {
			msg = "服务器错误";
			resCode = 500;
			e.printStackTrace();
		}
		
		return SUCCESS;
	}

	@Resource(name = "bookService")
	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	public void setJsonParam(String jsonParam) {
		this.jsonParam = jsonParam;
	}

	public List<Book> getBooks() {
		return books;
	}

	public int getResCode() {
		return resCode;
	}

	public String getMsg() {
		return msg;
	}
	
	
}
